<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Rag Hu
 * Created Time: 2019/7/18 9:50
 * Modified Time: 2019/7/18 9:50
 * Version: 2.0
 */

namespace App\Modules\Employee\Criterias;


use App\Lib\Utilities;
use Flower\Core\Repository\Contracts\RepositoryInterface;
use Flower\Core\Repository\Criterias\BaseCriterias;
use Illuminate\Support\Facades\DB;

class WxGetStoreDynamicListCriteria extends BaseCriterias
{
    protected $store_id;

    public function __construct($store_id)
    {
        $this->store_id = $store_id;
    }

    public function apply($model, RepositoryInterface $repository)
    {
        //查询出店铺所有理发师
        $store_id = $this->store_id;

        $barber = DB::table('user_store')
            ->select('uid')
            ->where('sid', $store_id)
            ->where('rid', 2)
            ->get()
            ->toArray();

        $barber = $this->getBarberIdList($barber);

        $select = [
            'hx_dynamic.id',
            'hx_dynamic.detail',
            'date_format(hx_dynamic.created_at,"%m") as month',
            'date_format(hx_dynamic.created_at,"%d") as day',
            'hx_dynamic.created_at'
        ];

        $select = implode($select, ',');

        $model = $model
            ->selectRaw($select)
            ->with(['resource' => function ($query) {
                $select = [
                    'hx_dynamic_resource.id',
                    'hx_dynamic_resource.dynamic_id',
                    'type',
                    'CASE WHEN type = 1 THEN hx_picture.image else hx_video.thumb END as image',
                    'CASE WHEN type = 1 THEN null else hx_video.url END as video',
                ];

                $select = implode($select, ',');

                $query->selectRaw($select)
                    ->leftJoin('picture', function ($join) {
                        $join->on('dynamic_resource.resource_id', '=', 'picture.id');

                    })
                    ->leftJoin('video', function ($join) {
                        $join->on('dynamic_resource.resource_id', '=', 'video.id');

                    });
            }])
            ->whereIn('user_id', $barber)
            ->where('store_id',$store_id)
            ->orderBy('dynamic.created_at','DESC');

        return $model;
    }

    //对象转数组
    protected function getBarberIdList($array)
    {
        $new_array = [];

        foreach ($array as $key => $value) {
            $value = array_values(get_object_vars($value));
            $new_array[] = $value[0];
        }

        return $new_array;
    }
}